#!/bin/bash

set -eux

FS_TYPE=`findmnt -o FSTYPE -fn /`

if [ "$FS_TYPE" = "xfs" ]; then
    xfs_growfs /
elif [ "$FS_TYPE" = "ext4" ]; then
    resize2fs {{ guest_partition }} || true
else
    echo "ERROR: Unknown filesystem, cannot resize."
    exit 1
fi

{% if not undercloud_setup|bool %}

{{ ansible_pkg_mgr }} clean all
{% if convert_image_update|bool %}
{{ ansible_pkg_mgr }} update -y
{% endif %}

{{ ansible_pkg_mgr }} remove -y {{ convert_image_remove_pkgs|join(" ") }}
{{ ansible_pkg_mgr }} install -y {{ convert_image_install_pkgs|join(" ") }}
{% if convert_image_tempest_plugins is defined and convert_image_tempest_plugins|length %}
{# keep plugins install isolated from previous yum install to ease debugging #}
{{ ansible_pkg_mgr }} install -y {{ convert_image_tempest_plugins|join(" ") }}
{% endif %}

{% endif %}

{% if overcloud_as_undercloud|bool %}
# Create ifcfg file if not exist, as it's removed in overcloud prep
# https://review.opendev.org/q/I3b8cb5f8c413c109da1228878db9cff4d439273b
if [ ! -f /etc/sysconfig/network-scripts/ifcfg-eth0 ]; then
cat >/etc/sysconfig/network-scripts/ifcfg-eth0<<EOF
DEVICE="eth0"
BOOTPROTO="dhcp"
ONBOOT="yes"
TYPE="Ethernet"
EOF
fi
{% endif %}

useradd {{ undercloud_user }}
echo "{{ undercloud_user }} ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/{{ undercloud_user }}
chmod 0440 /etc/sudoers.d/{{ undercloud_user }}

mkdir /home/{{ undercloud_user }}/.ssh

echo "127.0.0.1  undercloud localhost" > /etc/hosts
echo "HOSTNAME=undercloud" >> /etc/sysconfig/network
echo "undercloud" > /etc/hostname

chown -R {{ undercloud_user }}:{{ undercloud_user }} /home/{{ undercloud_user }}/

# Add a 4GB swap file to the Undercloud
dd if=/dev/zero of=/swapfile bs=1024 count=4194304
mkswap /swapfile
chmod 600 /swapfile
# Enable it on start
echo "/swapfile swap swap defaults 0 0" >> /etc/fstab

{% if not selinux_enforcing|bool %}

sed -i 's/SELINUX=enforcing/SELINUX=permissive/' /etc/selinux/config

{% endif %}
